package com.zjpavt.client.page;

import com.zjpavt.client.enums.ExtendDeviceEnum;
import com.zjpavt.client.extenddevice.voltagecurrent.ITemperatureAndHumidityDevice;
import com.zjpavt.client.hal.*;
import com.zjpavt.client.job.JobRunner;
import com.zjpavt.client.page.abstractpage.AbstractEditablePage;
import com.zjpavt.client.page.editableunit.EditUnitNum;
import com.zjpavt.client.page.pageunit.ScreenLine;
import com.zjpavt.client.util.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 第五页 温度显示页
 *
 * @author zyc
 */
@Slf4j
public class TemperaturePage extends AbstractEditablePage {
    public static final DecimalFormat REL_TIME_FORMAT = new DecimalFormat("00000");
    private static final String NULL_TEMP = "***";
    /**
     * 没有值的时候初始为00500 即500ms
     */
    private static final String DEFAULT_REL_TIME = "00500";
    private static final String REL_TIME = "rel_time";
    /**
     * 操作间隔时间
     */
    private int relTime = 500;
    private static final DecimalFormat TEMPERATURE_FORMAT = new DecimalFormat("000.00");



    public TemperaturePage(int pageNum, long mRefreshPeriod) {
        super(pageNum, mRefreshPeriod);
        getRelTimeString();
        LoopManager.getInstance().setIntervalTimeBetweenLoopChange(relTime);
    }

    @Override
    public void initEditUnits() {
        clearEditUnit();
        addEditUnit(new EditUnitNum(2, 12, 13, 0, 85, 1));
        addEditUnit(new EditUnitNum(3, 10, 14, 0, 99900, 100));
    }

    @Override
    public void setDefaultVal() {
        getEditUnit(0).setCurrentVal(SystemInnerTemperatureSensor.getInstance().getTmpThresholdLow());
        getEditUnit(1).setCurrentVal(relTime);
        if (ExtendDeviceManager.getInstance().containsExtendDevice(ExtendDeviceEnum.TMP)) {
            ITemperatureAndHumidityDevice sensor = (ITemperatureAndHumidityDevice) ExtendDeviceManager.getInstance().getExtendDevice(ExtendDeviceEnum.TMP);
        }
    }

    @Override
    public void saveVal() {
//        设备本机温度报警 阈值
        String sTemperatureLimit = getEditUnit(0).getText();
        String relTimeString = getEditUnit(1).getText();
        try {
//			获取到页面的值 单位为1°C  而设置的值为0.1°C
            int iRelTime = Integer.parseInt(relTimeString);
            int iTemperatureLimit = Integer.parseInt(sTemperatureLimit);
            saveRelTime(iRelTime);
            saveTemperatureLimit(iTemperatureLimit);
        } catch (Exception e) {
            log.error(LoggerUtil.convertException2String(e));
        }
    }

    @Override
    public void refreshPage() {
        String countDown = JobRunner.getInstance().getCountDownTime();
        double systemTemperature = 0;
        try {
            String temperatureString = SystemInnerTemperatureSensor.getInstance().getFormattedTmp();
            systemTemperature = Double.parseDouble(temperatureString);
        } catch (Exception e) {
//                如果没有读到显示0 温度为int类型单位为0.001
            log.error("get system TEMPERATURE_FORMAT fail! from " + ClientConfig.TMP_SENSOR_DEVICE_FILE_PATH);
        }
        LedScreen.getInstance().setText(getPageContent(systemTemperature, getFormatRelTime(), countDown));
    }
    DecimalFormat REL_TIME_DF = new DecimalFormat("00000");


    /**
     * 异常的时候返回NULL_REL_TIME
     * @return 获取缓存的开关时间间隔
     */
    protected String getRelTimeString() {
        String relTime;
        try {
            relTime = PropertiesUtil.getPropertiesDefault(REL_TIME);
        } catch (IOException e) {
            log.error(LoggerUtil.convertException2String(e));
            this.relTime = Integer.parseInt(DEFAULT_REL_TIME);
            return DEFAULT_REL_TIME;
        }
        if (relTime == null) {
            saveRelTime(Integer.parseInt(DEFAULT_REL_TIME));
            return DEFAULT_REL_TIME;
        } else {
            this.relTime = Integer.parseInt(relTime);
            return relTime;
        }
    }

    public void saveRelTime(int relTime) {
        try {
            if (this.relTime != relTime) {
                this.relTime = relTime;
                PropertiesUtil.setPropertyOrReplaceDefault(REL_TIME, REL_TIME_DF.format(relTime));
                LoopManager.getInstance().setIntervalTimeBetweenLoopChange(relTime);
            } else {
                return;
            }
        } catch (IOException e) {
            log.error(LoggerUtil.convertException2String(e));
        }
    }
    /**
     * 保存温度阈值
     * @param temperatureLimit 保存温度阈值
     */
    public void saveTemperatureLimit(int temperatureLimit) {
        SystemInnerTemperatureSensor.getInstance().setTmpThreshold(temperatureLimit);
    }

    /**
     * 获取间隔时间
     * @return
     */
    public int getRelTime() {
        return this.relTime;
    }

    /**
     *
     * @return 格式化的间隔时间 00500
     */
    protected String getFormatRelTime() {
        try {
            return REL_TIME_FORMAT.format(this.relTime);
        } catch (Exception e) {
            log.error(LoggerUtil.convertException2String(e));
            return DEFAULT_REL_TIME;
        }
    }

    @Override
    protected Runnable getRefreshTask() {
        //此处按块刷新，给每个可编辑块按照当前时间赋值，只有值变化时才刷新当前内容
        return () -> {
            refreshPage();
        };
    }

    /**
     * 不包含温湿度传感器的时候
     *
     * @param systemTemperature
     * @param relTime
     * @param countDown
     * @return
     */
    public List<ScreenLine> getPageContent(double systemTemperature, String relTime, String countDown) {
        List<ScreenLine> result = new ArrayList<>();
        String tmp = TEMPERATURE_FORMAT.format(systemTemperature);
        String tempLimit = SystemInnerTemperatureSensor.getInstance().getTmpThresholdLowFormat();
        result.add(new ScreenLine.ScreenLineBuilder().text("temp:" + "+" + tmp).pageNum(getPageNum()).build());
        result.add(new ScreenLine.ScreenLineBuilder().text("tempAlarm: " + tempLimit).build());
        if (StringUtil.isNullOrEmpty(relTime)) {
            relTime = DEFAULT_REL_TIME;
        }
        result.add(new ScreenLine.ScreenLineBuilder().text("Rel_time:" + relTime).build());
        result.add(new ScreenLine.ScreenLineBuilder().text(countDown).alignRight().build());
        return result;
    }

    @Override
    public void onKeyEnt() {
        super.onKeyEnt();
    }
}
